package cc.atliberty.Imagecaptcha;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

@WebServlet("/servlet/ChineseCheckCode")
public class ChineseCheckCode extends HttpServlet {
    public static final int WIDTH = 200;
    public static final int HEIGHT = 35;
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setContentType("img/jpeg;charset=utf-8");

        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = (Graphics2D) image.getGraphics();
        
        setBackgroundColor(g);
        setBorder(g);
        drawRandomLine(g);
        String randomNum = drawRandomNum(g);
        HttpSession session = request.getSession();
        session.setAttribute("checkcode",randomNum);
        
        response.setContentType("image/jpeg");
        response.setDateHeader("Expires", -1);
        response.setHeader("pragma", "no-cache");
        response.setHeader("cache-control", "no-cache");
        ImageIO.write(image, "jpg", response.getOutputStream());
    }
    private void setBackgroundColor(Graphics2D g) {
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, WIDTH, HEIGHT);
    }

    private void setBorder(Graphics2D g) {
        g.setColor(Color.BLUE);
        g.drawRect(1, 1, WIDTH - 2, HEIGHT - 2);
    }

    private void drawRandomLine(Graphics2D g) {
        g.setColor(Color.GREEN);
        for (int i = 0; i < 5; i++) {
            int x1 = new Random().nextInt(WIDTH);
            int y1 = new Random().nextInt(HEIGHT);
            int x2 = new Random().nextInt(WIDTH);
            int y2 = new Random().nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }
    }
    private String drawRandomNum(Graphics2D g) {
        //(1)设置随机显示值
        String ss = "2108054412刘源";
        g.setColor(Color.RED);
        g.setFont(new Font("宋体", Font.BOLD, 20));
        g.drawString(ss, 10,20);
        return ss;
    }
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet(request, response);
    }
}
